import { UploadOutlined } from '@ant-design/icons'
import { Button, message, Upload, Modal } from 'antd'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import React, { FC, useState } from 'react'
import { TPic } from '@/Type/type'
import axios from '@/http'
import { AxiosResponse, AxiosStatic } from 'axios'
type TPicFile = TPic & { file: RcFile }
const UploadPictureModal: FC<{ open: boolean; closeModal: (b: boolean) => void; getPicList: () => void }> = ({
  open,
  closeModal,
  getPicList
}) => {
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const [uploading, setUploading] = useState(false)
  const [picList, setPicture] = useState<TPicFile[]>([])
  const preImg = (files: RcFile[]) => {
    const promiseArr: Promise<TPicFile>[] = []
    files.forEach(file => {
      const promise = new Promise<TPicFile>((resolve, reject) => {
        let url = window.webkitURL || window.URL
        let imgfileurl = url.createObjectURL(file)
        const img = document.createElement('img')
        img.src = imgfileurl
        let width: number = 0
        let height: number = 0
        img.onload = e => {
          width = (e.target as HTMLImageElement).width
          height = (e.target as HTMLImageElement).height
          resolve({ file, url: imgfileurl, width, height })
        }
      })
      promiseArr.push(promise)
    })
    Promise.all(promiseArr).then(res => {
      setPicture([...picList, ...res])
    })
    return true
  }

  const handleCancel = () => {
    handleReset()
    closeModal(false)
  }

  const handleUpload = () => {
    const uploadArr: Promise<AxiosResponse<any, any>>[] = []
    picList.forEach(item => {
      const formData = new FormData()
      formData.append('picFile', item.file)
      formData.append('width', item.width + '')
      formData.append('height', item.height + '')
      const promiseItem = axios.post('/pic/add', formData)
      uploadArr.push(promiseItem)
    })
    setUploading(true)
    Promise.all(uploadArr)
      .then(res => {
        if (res.every(item => item.data.error === -1)) {
          getPicList()
          message.success('上传成功')
          handleCancel()
        } else {
          message.error('上传失败')
        }
      })
      // You can use any AJAX library you like
      .catch(() => {
        message.error('上传失败')
      })
      .finally(() => {
        setUploading(false)
      })
  }

  const props: UploadProps = {
    onRemove: file => {
      const index = fileList.indexOf(file)
      const newFileList = fileList.slice()
      const newPicList = picList.slice()
      newFileList.splice(index, 1)
      newPicList.splice(index, 1)
      setFileList(newFileList)
      setPicture(newPicList)
    },
    beforeUpload: (file, fileLists) => {
      setFileList([...fileList, ...fileLists])
      preImg(fileLists)
      return false
    },
    fileList,
    multiple: true
  }
  const handleReset = () => {
    setFileList([])
    setPicture([])
  }
  return (
    <>
      <Modal
        visible={open}
        title="图片上传"
        onCancel={handleCancel}
        footer={
          <>
            <Button key="back" onClick={handleCancel}>
              取消
            </Button>
            <Button key="reset" onClick={handleReset}>
              重置
            </Button>
            <Button key="upload" type="primary" onClick={handleUpload} disabled={fileList.length === 0} loading={uploading}>
              {uploading ? 'Uploading' : '开始上传'}
            </Button>
          </>
        }
      >
        <Upload {...props}>
          <Button icon={<UploadOutlined />}>挑选文件</Button>
        </Upload>
        {picList.map((item, index) => (
          <img key={index} style={{ width: '200px', height: '150px' }} src={item.url} alt="" />
        ))}
      </Modal>
    </>
  )
}
export default UploadPictureModal
